import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/task.dart';
import '../models/member.dart';
import '../providers/task_provider.dart';
import '../providers/member_provider.dart';

class EditTaskDialog extends StatefulWidget {
  final Task task;

  const EditTaskDialog({super.key, required this.task});

  @override
  State<EditTaskDialog> createState() => _EditTaskDialogState();
}

class _EditTaskDialogState extends State<EditTaskDialog> {
  late TextEditingController _titleController;
  late TextEditingController _descriptionController;
  DateTime? _dueDate;
  Color _selectedColor = Colors.blue;
  TaskPriority _selectedPriority = TaskPriority.medium;
  String? _selectedMemberId;
  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    _titleController = TextEditingController(text: widget.task.title);
    _descriptionController = TextEditingController(text: widget.task.description);
    _dueDate = widget.task.dueDate;
    _selectedColor = widget.task.color;
    _selectedPriority = widget.task.priority;
    _selectedMemberId = widget.task.assignedTo;

    // 预加载成员列表
    Future.microtask(() {
      Provider.of<MemberProvider>(context, listen: false).loadMembers();
    });
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('编辑任务'),
      content: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 标题输入
              TextFormField(
                controller: _titleController,
                decoration: const InputDecoration(
                  labelText: '标题',
                  icon: Icon(Icons.title),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入任务标题';
                  }
                  return null;
                },
              ),

              const SizedBox(height: 16),

              // 描述输入
              TextFormField(
                controller: _descriptionController,
                decoration: const InputDecoration(
                  labelText: '描述',
                  icon: Icon(Icons.description),
                ),
                maxLines: 3,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入任务描述';
                  }
                  return null;
                },
              ),

              const SizedBox(height: 16),

              // 截止日期选择
              ListTile(
                leading: const Icon(Icons.calendar_today),
                title: Text(_dueDate == null ? '选择截止日期' : 
                  '${_dueDate!.year}-${_dueDate!.month}-${_dueDate!.day}'),
                onTap: () async {
                  final date = await showDatePicker(
                    context: context,
                    initialDate: _dueDate ?? DateTime.now(),
                    firstDate: DateTime.now(),
                    lastDate: DateTime.now().add(const Duration(days: 365)),
                  );
                  if (date != null) {
                    setState(() => _dueDate = date);
                  }
                },
                trailing: _dueDate == null ? null : IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: () => setState(() => _dueDate = null),
                ),
              ),

              const SizedBox(height: 16),

              // 颜色选择
              Row(
                children: [
                  const Icon(Icons.color_lens),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Wrap(
                      spacing: 8,
                      children: [
                        Colors.blue,
                        Colors.red,
                        Colors.green,
                        Colors.orange,
                        Colors.purple,
                        Colors.teal,
                      ].map((color) => InkWell(
                        onTap: () => setState(() => _selectedColor = color),
                        child: Container(
                          width: 32,
                          height: 32,
                          decoration: BoxDecoration(
                            color: color,
                            shape: BoxShape.circle,
                            border: _selectedColor == color
                                ? Border.all(color: Colors.black, width: 2)
                                : null,
                          ),
                        ),
                      )).toList(),
                    ),
                  ),
                ],
              ),

              const SizedBox(height: 16),

              // 优先级选择
              Row(
                children: [
                  const Icon(Icons.priority_high),
                  const SizedBox(width: 16),
                  Expanded(
                    child: SegmentedButton<TaskPriority>(
                      segments: const [
                        ButtonSegment(
                          value: TaskPriority.low,
                          label: Text('低'),
                        ),
                        ButtonSegment(
                          value: TaskPriority.medium,
                          label: Text('中'),
                        ),
                        ButtonSegment(
                          value: TaskPriority.high,
                          label: Text('高'),
                        ),
                      ],
                      selected: {_selectedPriority},
                      onSelectionChanged: (Set<TaskPriority> selection) {
                        setState(() => _selectedPriority = selection.first);
                      },
                    ),
                  ),
                ],
              ),

              const SizedBox(height: 16),

              // 负责人选择
              Consumer<MemberProvider>(
                builder: (context, memberProvider, child) {
                  return FutureBuilder<List<Member>>(
                    future: memberProvider.members.isEmpty 
                        ? memberProvider.loadMembers() 
                        : Future.value(memberProvider.members),
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return const Center(
                          child: SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          ),
                        );
                      }

                      if (snapshot.hasError) {
                        return const Text('加载成员失败');
                      }

                      final members = snapshot.data ?? [];
                      
                      return DropdownButtonFormField<String>(
                        decoration: const InputDecoration(
                          labelText: '负责人',
                          icon: Icon(Icons.person),
                        ),
                        value: _selectedMemberId,
                        items: [
                          const DropdownMenuItem<String>(
                            value: null,
                            child: Text('未分配'),
                          ),
                          ...members.map((member) => DropdownMenuItem<String>(
                            value: member.id,
                            child: Text(member.name),
                          )),
                        ],
                        onChanged: (value) {
                          setState(() => _selectedMemberId = value);
                        },
                      );
                    },
                  );
                },
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: () {
            if (_formKey.currentState!.validate()) {
              final updatedTask = widget.task.copyWith(
                title: _titleController.text,
                description: _descriptionController.text,
                dueDate: _dueDate,
                color: _selectedColor,
                priority: _selectedPriority,
                assignedTo: _selectedMemberId,
              );

              Provider.of<TaskProvider>(context, listen: false)
                  .updateTask(updatedTask);

              Navigator.pop(context);
            }
          },
          child: const Text('保存'),
        ),
      ],
    );
  }
} 